package com.briup.ch11;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Properties;

/**
 * @Author briup-adam
 * @Date 2023/10/24 下午5:19
 * @Description
 **/

public class PropertiesDemo {
    static class Stu {
        private String name;
        private int age;
        private String hobby;

        @Override
        public String toString() {
            return "Stu{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", hobby='" + hobby + '\'' +
                    '}';
        }

        public Stu(String name, int age, String hobby) {
            this.name = name;
            this.age = age;
            this.hobby = hobby;
        }
    }

    public static void main(String[] args) {
        //创建集合对象
        Properties p = new Properties();
        System.out.println(p);
        //输入流
        FileInputStream fis = null;
        InputStreamReader isr = null;
        PrintWriter pw = null;
        try {
            fis = new FileInputStream("02code/src/02.properties");

            isr = new InputStreamReader(fis, "UTF8");
            p.load(isr);
            System.out.println(p);

            //从集合中根据key获取value
//            Object o = p.get("stuName");
            String name = p.getProperty("stuName");
            String hobby = p.getProperty("hobby");
            int age = Integer.parseInt(p.getProperty("age"));
            Stu stu = new Stu(name, age, hobby);
            System.out.println(stu);
            p.setProperty("gender", "男");
            p.setProperty("address", "内蒙古呼和浩特市托克托县");
            p.setProperty("tel", "18876777899");
            pw = new PrintWriter("02code/src/02.properties");
            //将集合内容持久化到磁盘
            p.store(pw, "添加一部分属性");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr != null)
                    isr.close();
                if (fis != null)
                    fis.close();
                if (pw != null)
                    pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
